<template>
  <div class="expression-designer">
    <div class="prompt">
      <p class="p"
        >备注：字段选择范围为本功能内部字段，且可以通过{parent.字段编码}的形式获取主功能
        表单字段值。也可通过例如{@USER_ID@}的方式得到全局变量。</p
      >
    </div>

    <div class="tableWrap">
      <je-table
        ref="xTable11"
        border
        stripe
        auto-resize
        sync-resize
        show-overflow="ellipsis"
        keep-source
        height="200"
        show-header-overflow
        resizable
        header-align="center"
        :edit-rules="validRules"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showUpdateStatus: true,
          showStatus: false,
        }"
        :row-config="{ isCurrent: true, isHover: true }"
        :store="tableData"
        size="mini"
        @current-change="getCurrentData"
      >
        <je-table-column width="40" align="center">
          <template #header>
            <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addColumn"></i>
          </template>
          <template #default="{ row }">
            <i
              style="font-size: 16px; cursor: pointer"
              class="fal fa-times"
              @click="deleteColumn(row)"
            ></i>
          </template>
        </je-table-column>
        <je-table-column
          field="text"
          title="字段|系统变量"
          width="220"
          align="center"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <je-grid-select
              v-model:value="row.text"
              name="text"
              :editable="true"
              config-info="JE_CORE_RESOURCEFIELD"
              :querys="funcQueryName"
              @select="selectData"
            />
            <!-- <div class="inputWrap">
              <je-input v-model:value="row.text" />
              <i class="setIcon fal fa-cog"></i>
            </div> -->
          </template>
        </je-table-column>
        <je-table-column
          field="expression"
          title="表达式"
          width="140"
          align="center"
          :edit-render="{}"
        >
          <template #edit="{ row }">
            <je-select
              v-model:value="row.expression"
              :get-popup-container="getPopupContainer"
              config-info="JE_FUNC_FIELD_EXPTYPE,row.expression,code,S"
            ></je-select>
          </template>
          <template #default="{ row }">{{ row.expression }}</template>
        </je-table-column>
        <je-table-column
          field="value"
          title="值"
          align="center"
          :edit-render="{ autofocus: '.ant-input' }"
        >
          <template #edit="{ row }">
            <je-input v-model:value="row.value" />
          </template>
        </je-table-column>
        <je-table-column field="type" title="值类型" width="220" align="center" :edit-render="{}">
          <template #edit="{ row }">
            <je-select
              v-model:value="row.type"
              :get-popup-container="getPopupContainer"
              :options="[
                {
                  label: '字符型',
                  value: false,
                },
                {
                  label: '数值型',
                  value: true,
                },
              ]"
            />
          </template>
          <template #default="{ row }">
            {{ row.type ? '数值型' : '字符型' }}
          </template>
        </je-table-column>
      </je-table>
    </div>

    <div class="generateClick">
      <je-button
        icon="fal fa-angle-double-up"
        class="span up"
        type="text"
        style="margin-right: 40px"
        @click="FormatExpression('up')"
      >
        导入表达式
      </je-button>
      <je-button
        icon="fal fa-angle-double-down"
        class="span up"
        type="text"
        @click="FormatExpression('down')"
      >
        生成表达式
      </je-button>
    </div>
    <je-textarea v-model:value.trim="expressionTextareaValue" allow-clear :rows="4" />
  </div>
</template>

<script>
  import { toRefs, reactive, defineComponent, ref, onMounted } from 'vue';
  import { Grid, Input, Select, InputSelect, Data, Button } from '@jecloud/ui';
  import { isEmpty } from '@jecloud/utils';

  export default defineComponent({
    name: 'ExpressionDesigner',
    components: {
      JeInput: Input,
      JeTextarea: Input.TextArea,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
      JeSelect: Select,
      JeGridSelect: InputSelect.Grid,
      jeButton: Button,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['changeModal'],
    setup(props) {
      const state = reactive({
        visible: props.visble,
        xTable11: ref(),
        title: '表达式设计器',
        tableData: Data.Store.useGridStore({
          data: [],
        }),
        validRules: ref({
          text: [{ required: true, message: '该输入项为必填项' }],
          expression: [{ required: true, message: '该输入项为必填项' }],
        }),
        currentData: {}, // 表格当前选中的数据
        expressionValue: [],
        expressionTextareaValue: props.recordData.value,
        funcQueryName: [
          {
            code: 'RESOURCEFIELD_XTYPE',
            type: 'notIn',
            value: ['child', 'fieldset', 'childfuncfield', 'uxdisplayfield'],
          },
          { code: 'RESOURCEFIELD_FUNCINFO_ID', type: '=', value: props.recordData.funcId },
        ],
      });
      // 查询参数table增加
      const addColumn = async () => {
        const record = {
          text: '',
          type: false,
          value: '',
          expression: '',
        };
        await state.xTable11.insertAt(record, -1);
      };

      const methods = {
        getPopupContainer() {
          return document.body;
        },
        // 获取当前选中的table的row
        getCurrentData({ row }) {
          state.currentData = row;
        },
        selectData({ rows }) {
          state.currentData.text = `{${rows[0].RESOURCEFIELD_CODE}}`;
        },
        // 生成表达式
        FormatExpression(type) {
          if (type == 'down') {
            state.expressionValue = [];
            state.expressionTextareaValue = '';
            // 1获取数据
            const data = state.xTable11.getTableData().tableData;
            if (!data.length) {
              return false;
            }
            // 2校验数据
            state.xTable11.validate(data, (errMap) => {
              if (errMap) {
                return false;
              }
              // 3.遍历数据，进行拼接
              data.forEach((item) => {
                let formatitem = '';
                // 先去判断type类型是不是数值类型，如果是，那就需要将test数值类型
                const text = item.type ? item.text : `'${item.text}'`;
                // 在看一下拼接格式
                if (['isEmpty', 'isNotEmpty'].includes(item.expression)) {
                  item.value = '';
                  formatitem = `JE.${item.expression}(${text})`;
                } else if (item.expression == 'indexOf') {
                  formatitem = `${text}.${item.expression}(${
                    item.type ? item.value : `'${item.value}'`
                  })!=-1`;
                } else {
                  formatitem = `${text} ${item.expression} ${
                    item.type ? item.value : `'${item.value}'`
                  }`;
                }
                state.expressionValue.push(formatitem);
              });
              state.expressionTextareaValue = state.expressionValue.join(' && ');
              state.xTable11.store.loadData(data);
            });
          }
          if (type == 'up') {
            methods.buildTableData(state.expressionTextareaValue);
          }
        },
        // 通过props.recordData.value来进行数据的回显
        buildTableData(dataStr) {
          if (isEmpty(dataStr)) return;
          //根据&&符号将字符串切割为数组
          const dataArr = dataStr.split('&&');
          state.tableData.data = [];
          dataArr.map((item) => {
            const obj = {
              text: '',
              type: false,
              value: '',
              expression: '',
            };
            // 先获取字段｜系统变量里面的值
            const flag = [
              'JE.isEmpty',
              'JE.isNotEmpty',
              'JE.useUtils().isEmpty',
              'JE.useUtils().isNotEmpty',
            ].some((item_) => item.includes(item_));
            if (flag) {
              //获取()指定的位置
              const leftpos = item.indexOf('(') + 1;
              const rightpos = item.lastIndexOf(')');
              const str = item.substring(leftpos, rightpos);
              if (!str.startsWith("'")) {
                obj.type = true;
                obj.text = str;
              } else {
                obj.text = item.substring(leftpos + 1, rightpos - 1);
              }
              obj.value = '';

              obj.expression = item.substring(item.lastIndexOf('.') + 1, item.lastIndexOf('('));
            } else if (item.includes('indexOf')) {
              item = item.trim();
              obj.expression = 'indexOf';
              obj.text = /['||"]/.test(item)
                ? item.substring(1, item.indexOf('.') - 1)
                : item.substring(0, item.indexOf('.'));

              const str = item.substring(item.indexOf('(') + 1, item.indexOf(')'));
              if (/['||"]/.test(str)) {
                obj.value = str.substring(1, str.length - 1);
                obj.type = false;
              } else {
                obj.value = str;
                obj.type = true;
              }
            } else if (['==', '>', '>=', '<', '<=', '!='].some((item_) => item.includes(item_))) {
              const sign = ['==', '>', '>=', '<', '<=', '!='].find((item_) => item.includes(item_));
              const signArr = item.split(sign);
              const signValue = signArr[1].trim();
              obj.text = /['||"]/.test(signArr[0])
                ? signArr[0].substring(1, signArr[0].length - 2)
                : signArr[0].trim();
              if (/['||"]/.test(signValue)) {
                obj.value = signValue.substring(1, signValue.length - 1);
                obj.type = false;
              } else {
                obj.value = signValue;
                obj.type = true;
              }
              obj.expression = sign;
            }
            state.tableData.data.push(obj);
          });
        },
        deleteColumn(record) {
          state.xTable11.remove(record);
        },
      };
      onMounted(() => {
        // 刚进入页面，通过props.recordData.value来进行数据的回显
        methods.buildTableData(props.recordData.value);
      });
      return {
        addColumn,
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less" scoped>
  .expression-designer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
        cursor: pointer;
      }
    }
    .prompt {
      padding: 20px;
      border: 1px solid #b8741a;
      background: #faf9da;
      color: #b8741a;
      .title {
        color: #36761f;
      }
      .p {
        margin: 0;
        line-height: 1.4;
      }
    }
    .tableWrap {
      margin: 20px 0;
      height: 200px;
    }
    .generateClick {
      display: flex;
      justify-content: center;
      margin: 20px 0;

      .span {
        color: #2a6fd0;
        font-size: 16px;
        font-weight: bold;
        .fal {
          margin: 0 10px 0 0;
        }
      }
    }
  }
</style>
